package cn.bs.seckill.config;

import cn.bs.seckill.pojo.User;
import cn.bs.seckill.service.UserService;
import cn.bs.seckill.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableWebMvc
//自定义用户参数
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    //如果满足这个方法里面的判断条件,才会走下面那个方法
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> parameterType = parameter.getParameterType();
        //判断参数是否是User类型的
        return User.class==parameterType;
    }

    //这个方法就用来拿用户的数据
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        //拿到HttpServletRequset
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String userUUID = CookieUtil.getCookieValue(request, "userUUID");
        if(StringUtils.isEmpty(userUUID)){
            return null;
        }

        return userService.getUserByCookie(userUUID);
    }
}
